import re
import os
import pathlib
import keyword
if __name__ == "__main__":
    import McEventScraper as mes
else:
    from . import McEventScraper as mes

lambda: "自动化事件代码生成工具 By Zero123"

EVENT_NAMED_MAP = {
    "世界": "World",
    "实体": "Entity",
    "玩家": "Player",
    "方块": "Block",
    "物品": "Item",
    "模型": "Model",
    "UI": "UI",
    "音效": "Sound",
    "控制": "Control",
    "联机大厅": "MultiplayerLobby",
}

_TYPE_INFO_MAP = {  # Fuck Nethard
    "Int": "int",
    "Float": "float",
    "List": "list",
    "Dict": "dict",
    "int/long": "int",
    "int/float": "float",
    "list[string,...]": "list[str]",
    "list[[x,y,z],...]": "list[list[float | int]]",
    "list[[x,y,z,cancel],...]": "list[list[float | int, float | int, float | int, bool]]",
    """[{"blockName":str,"posX":int,"posY":int,"posZ":int}...]/None""": "list[dict] | None",   # what?
}

def getCurrentDir() -> str:
    """ 获取当前脚本所在目录 """
    return str(pathlib.Path(__file__).parent.resolve())

def formatTypeInfo(typeInfo: str) -> str:
    """ 格式化类型信息 """
    if typeInfo in _TYPE_INFO_MAP:
        typeInfo = _TYPE_INFO_MAP[typeInfo]
    if "(" in typeInfo and ")" in typeInfo:
        typeInfo = typeInfo.replace("(", "[").replace(")", "]")
    typeInfo = typeInfo.replace("/", " | ") # Fuck Nethard
    return normalizeBacketList(typeInfo)

def normalizeBacketList(s: str) -> str:
    """ 将字符串中 [] 内部的内容按逗号规整化 """
    def replacer(match):
        inner = match.group(1)
        items = [item.strip() for item in inner.split(',') if item.strip()]
        return "[" + ", ".join(items) + "]"
    result = re.sub(r"\[([^\[\]]*)\]", replacer, s)
    return result

def generateEventCode(doc: mes.EventDoc) -> str:
    """ 生成事件代码 """
    eventDoc = doc.getEventDesc()
    eventCode = f"""class {doc.getEventName()}(object):
    \"\"\" {eventDoc.getDescText()} \"\"\"
    def __init__(self, args=None):
        self.mArgs = args or dict()\n"""
    argsList = eventDoc.getArgsDesc()
    codeBuf = []
    for arg in argsList:
        name = arg.attrName
        desc = arg.attrDesc
        typeInfo = formatTypeInfo(arg.attrType)
        codeBuf.append(f"""    @property
    def {formatKeyWorld(name)}(self):
        # type: () -> {typeInfo}
        \"\"\" {desc} \"\"\"
        return self.mArgs.get(\"{name}\")
""")
    if codeBuf:
        eventCode += "\n" + "\n".join(codeBuf)
    return eventCode

def formatKeyWorld(key: str) -> str:
    if keyword.iskeyword(key):
        key = "_" + key
    return key

def autoGen():
    targetPath = pathlib.Path(os.path.join(getCurrentDir(), "MCEventModule"))
    if not targetPath.exists():
        targetPath.mkdir(parents=True, exist_ok=True)
    initFile = targetPath / "__init__.py"
    if not initFile.exists():
        initFile.touch()
    print("正在抓取事件数据...")
    eventMap = mes.AUTO_GEN_ALL_EVENTS()
    codeMap: dict[str, list] = {}
    for eventType, eventList in eventMap.items():
        print(f"正在生成 {eventType} 事件代码...")
        eventFullType = EVENT_NAMED_MAP.get(eventType, "Unknow")
        for event in eventList:
            code = generateEventCode(event)
            if not eventFullType in codeMap:
                codeMap[eventFullType] = []
            codeMap[eventFullType].append(code)
    for eventType, codeList in codeMap.items():
        filePath = targetPath / f"{eventType}.py"
        with open(filePath, "w", encoding="utf-8") as f:
            f.write("# -*- coding: utf-8 -*-\n# Generated By QuMod McEventCodeGen.py\n\n")
            f.write("\n".join(codeList))
        print(f"{eventType} 事件代码生成完毕, 文件路径: {filePath}")
    with open(targetPath / "AllEvents.py", "w", encoding="utf-8") as f:
        f.write("# -*- coding: utf-8 -*-\n# Generated By QuMod McEventCodeGen.py\n\n")
        for eventType in codeMap.keys():
            f.write(f"from .{eventType} import *\n")

if __name__ == "__main__":
    autoGen()